package com.michael.demos.base.thread.other;

import java.util.concurrent.TimeUnit;

/**
 * 类功能描述:
 * <pre>
 *   优雅停机 - DEMO
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/8/7 9:18
 */
public class ShutdownHookDemo {
    private ShutdownHook shutdownHook;

    public ShutdownHookDemo() {
        this.shutdownHook = new ShutdownHook(Thread.currentThread());
    }

    public void execute() {
        while (!shutdownHook.isReceivedSignal) {
            System.out.println("I am sleep");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I am not sleep");
        }
        System.out.println("end execute");
    }

    public static void main(String[] args) {
        ShutdownHookDemo app = new ShutdownHookDemo();
        System.out.println("start of main()");
        //do something.
        app.execute();
        System.out.println("End of main()");
    }
}

class ShutdownHook extends Thread {

    public boolean isReceivedSignal = false;
    private Thread mainThread;

    @Override
    public void run() {
        System.out.println("Shut down signal received.");
        this.isReceivedSignal = true;
        try {
            //do something.
            TimeUnit.SECONDS.sleep(1);
            mainThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Shut down complete.");
    }

    public ShutdownHook(Thread mainThread) {
        this.mainThread = mainThread;
        Runtime.getRuntime().addShutdownHook(this);
    }
}
